package dao;

import entity.Customer;
import db.DBUnit;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 顾客dao
 */
public class CustomerDao {
    /**
     * 顾客登录
     * @param conn
     * @param customer
     * @return resultCustomer
     * @throws Exception
     */
    public Customer login(Connection conn, Customer customer) throws Exception {
        Customer resultCustomer = null;
        String sql = "select * from customer where id=? and password=?";//通过密码和ID验证登录
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, customer.getId());//填入sql语句id=?
        pstmt.setString(2, customer.getPassword());
        ResultSet rs = pstmt.executeQuery();
        //若成功则将数据库中该用户的信息全部返回给resultCustomer
        if(rs.next()) {
            resultCustomer = new Customer();
            resultCustomer.setId(rs.getInt("id"));
            resultCustomer.setPassword(rs.getString("password"));
            resultCustomer.setTelNumber(rs.getString("telNumber"));
            resultCustomer.setAddress(rs.getString("address"));
        }
        return resultCustomer;
    }
    /**
     * 测试登录
     */
    public Customer testLogin(int id, String password) {
		DBUnit dbUnit = new DBUnit();
		Connection conn = dbUnit.getConnection();
		if(conn == null) {
			System.out.println("数据库连接失败！");
			return null;
		}
		Customer customer = new Customer();
		customer.setId(id);
		customer.setPassword(password);
        try {
            customer = new CustomerDao().login(conn, customer);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("登录失败！");
        }
//        System.out.print(customer.getAddress());//不为null则登录成功
        return customer;
    }
    
    public static void main(String[] args) {
    	CustomerDao customerdao = new CustomerDao();
		customerdao.testLogin(123,"123");
    }
}
